package cn.com.shadowless.xinning.view.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.mengpeng.mphelper.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import cn.com.shadowless.xinning.MyApplication;
import cn.com.shadowless.xinning.R;
import cn.com.shadowless.xinning.adapter.CostAdapter;
import cn.com.shadowless.xinning.adapter.TravelAdapter;
import cn.com.shadowless.xinning.callback.RequestCallBack;
import cn.com.shadowless.xinning.model.RequestResult;
import cn.com.shadowless.xinning.model.order.ChildResult;
import cn.com.shadowless.xinning.model.order.TravelOrderInfo;
import cn.com.shadowless.xinning.presenter.OrderPresenter;
import cn.com.shadowless.xinning.utils.PreferencesUtils;
import cn.com.shadowless.xinning.view.BaseFragment;
import cn.com.shadowless.xinning.view.activity.OfficeActivity;
import cn.com.shadowless.xinning.view.activity.TabActivity;

/**
 * The type Travel fragment.
 *
 * @author sHadowLess
 */
public class TravelFragment extends BaseFragment {
    /**
     * The Travel receipt info receipt num.
     */
    @BindView(R.id.travel_receiptInfo_ReceiptNum)
    TextView travelReceiptInfoReceiptNum;
    /**
     * The Travel receipt info make time.
     */
    @BindView(R.id.travel_receiptInfo_MakeTime)
    TextView travelReceiptInfoMakeTime;
    /**
     * The Travel receipt info maker.
     */
    @BindView(R.id.travel_receiptInfo_Maker)
    TextView travelReceiptInfoMaker;
    /**
     * The Travel receipt info making depart.
     */
    @BindView(R.id.travel_receiptInfo_MakingDepart)
    TextView travelReceiptInfoMakingDepart;
    /**
     * The Travel receipt info position job.
     */
    @BindView(R.id.travel_receiptInfo_PositionJob)
    TextView travelReceiptInfoPositionJob;
    /**
     * The Travel personal details proposer.
     */
    @BindView(R.id.travel_personalDetails_Proposer)
    TextView travelPersonalDetailsProposer;
    /**
     * The Travel personal details proposer depart.
     */
    @BindView(R.id.travel_personalDetails_ProposerDepart)
    TextView travelPersonalDetailsProposerDepart;
    /**
     * The Travel personal details position.
     */
    @BindView(R.id.travel_personalDetails_Position)
    TextView travelPersonalDetailsPosition;
    /**
     * The Travel personal details sex.
     */
    @BindView(R.id.travel_personalDetails_Sex)
    TextView travelPersonalDetailsSex;
    /**
     * The Travel personal details phone.
     */
    @BindView(R.id.travel_personalDetails_Phone)
    TextView travelPersonalDetailsPhone;
    /**
     * The Travel schedule date.
     */
    @BindView(R.id.travel_schedule_Date)
    TextView travelScheduleDate;
    /**
     * The Travel schedule expense department.
     */
    @BindView(R.id.travel_schedule_ExpenseDepartment)
    TextView travelScheduleExpenseDepartment;
    /**
     * The Travel schedule departure area.
     */
    @BindView(R.id.travel_schedule_departureArea)
    TextView travelScheduleDepartureArea;
    /**
     * The Travel schedule destination.
     */
    @BindView(R.id.travel_schedule_Destination)
    TextView travelScheduleDestination;
    /**
     * The Travel schedule trip allowances.
     */
    @BindView(R.id.travel_schedule_TripAllowances)
    TextView travelScheduleTripAllowances;
    /**
     * The Travel work plan.
     */
    @BindView(R.id.travel_workPlan)
    LinearLayout travelWorkPlan;
    /**
     * The Travel travel sum travel total.
     */
    @BindView(R.id.travel_travelSum_TravelTotal)
    TextView travelTravelSumTravelTotal;
    /**
     * The Travel budget info travel crash.
     */
    @BindView(R.id.travel_budgetInfo_TravelCrash)
    TextView travelBudgetInfoTravelCrash;
    /**
     * The Travel check process.
     */
    @BindView(R.id.travel_check_Process)
    LinearLayout travelCheckProcess;
    /**
     * The Travel travel sum real travel total.
     */
    @BindView(R.id.travel_travelSum_realTravelTotal)
    TextView travelTravelSumRealTravelTotal;
    /**
     * The Travel tab item travel cost.
     */
    @BindView(R.id.travel_tab_item_travelCost)
    LinearLayout travelTabItemTravelCost;
    /**
     * The Travel schedule is stay.
     */
    @BindView(R.id.travel_schedule_isStay)
    TextView travelScheduleIsStay;
    /**
     * The Travel schedule stay way.
     */
    @BindView(R.id.travel_schedule_stayWay)
    TextView travelScheduleStayWay;
    /**
     * The Travel schedule stay date.
     */
    @BindView(R.id.travel_schedule_stayDate)
    TextView travelScheduleStayDate;
    /**
     * The Travel schedule stay days.
     */
    @BindView(R.id.travel_schedule_stayDays)
    TextView travelScheduleStayDays;
    /**
     * The Travel attach info.
     */
    @BindView(R.id.travel_attachInfo)
    RecyclerView travelAttachInfo;
    /**
     * The Travel is stay info.
     */
    @BindView(R.id.travel_isStayInfo)
    LinearLayout travelIsStayInfo;

    /**
     * The Travel travel check process.
     */
    @BindView(R.id.travel_travelCheck_Process)
    LinearLayout travelTravelCheckProcess;

    private final String forMat = "%s\n预算总金额：%s\n已报销：%s\n报销中：%s\n剩余可报销：%s\n已申请未报销：%s\n在申请未报销：%s\n剩余可申请：%s";


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_travel_layout;
    }

    @Override
    protected void initData() {
        Bundle bundle = getArguments();
        if (null != bundle) {
            String orderId = bundle.getString("orderId");
            String userName = bundle.getString("userName");
            String billCode = bundle.getString("billCode");
            initTravelInfo(orderId, userName, billCode);
        }
    }

    @Override
    protected void initView() {

    }

    private void initTravelInfo(String orderId, String userName, String billCode) {
        OrderPresenter
                .getSingleton()
                .getTravelInfo(orderId, userName, new RequestCallBack<TravelOrderInfo>() {
                    @Override
                    public void success(RequestResult<TravelOrderInfo> result) {
                        String token = result.getLoginToken();
                        String oldToken = PreferencesUtils.getString(MyApplication.getInstance(), "token", "-1");
                        if (result.isSucceed() && null != result.getResult()) {
                            if (null != token && token.equals(oldToken)) {
                                Log.e(TAG, "success: " + result.toString());
                                TravelOrderInfo.DataBean dataBean = result.getResult().getData();
                                TravelOrderInfo.DataBean.CreateUserObjectBean createUserObjectBean = dataBean.getCreateUserObject();
                                TravelOrderInfo.DataBean.BudgetItemObjectBean budgetItemObjectBean = dataBean.getBudgetItemObject();
                                List<TravelOrderInfo.DataBean.HistoryListBean> historyListBeans = dataBean.getHistoryList();
                                List<TravelOrderInfo.DataBean.WorkPlanListBean> workPlanListBeans = dataBean.getWorkPlanList();
                                List<TravelOrderInfo.DataBean.ExpenseListBean> expenseListBeans = dataBean.getExpenseList();
                                List<TravelOrderInfo.DataBean.ComListBean> comListBeans = dataBean.getComList();
                                List<TravelOrderInfo.DataBean.FileListDTO> fileList = dataBean.getFileList();

                                String id = dataBean.getId();
                                String createTimeStr = dataBean.getCreateTimeStr();
                                String userName = createUserObjectBean.getUserName();
                                String departmentName = createUserObjectBean.getDepartmentName();
                                String positionName = createUserObjectBean.getPositionName();
                                travelReceiptInfoReceiptNum.setText(id);
                                travelReceiptInfoMakeTime.setText(createTimeStr);
                                travelReceiptInfoMaker.setText(userName);
                                travelReceiptInfoMakingDepart.setText(departmentName);
                                travelReceiptInfoPositionJob.setText(positionName);

                                String genderStr = createUserObjectBean.getGenderStr();
                                String telephone = createUserObjectBean.getTelephone();
                                travelPersonalDetailsProposer.setText(userName);
                                travelPersonalDetailsProposerDepart.setText(departmentName);
                                travelPersonalDetailsPosition.setText(positionName);
                                travelPersonalDetailsSex.setText(genderStr);
                                travelPersonalDetailsPhone.setText(telephone);

                                String departmentCostName = dataBean.getDepartmentCostName();
                                String startAddress = dataBean.getStartAddress();
                                String endAddress = dataBean.getEndAddress();
                                String travelTypeName = dataBean.getTravelTypeName();
                                String stayTypeName = dataBean.getStayTypeName();
                                String stayRangeStr = dataBean.getStayRangeStr();
                                String stayDays = dataBean.getStayDays();
                                boolean isStay = dataBean.isStay();
                                for (TravelOrderInfo.DataBean.ExpenseListBean expenseListBean : expenseListBeans) {
                                    String expenseDateRange = expenseListBean.getExpenseDateRange();
                                    travelScheduleDate.setText(expenseDateRange);
                                }
                                if (isStay) {
                                    travelIsStayInfo.setVisibility(View.VISIBLE);
                                    travelScheduleIsStay.setText("是");
                                    travelScheduleStayWay.setText(stayTypeName);
                                    travelScheduleStayDate.setText(stayRangeStr);
                                    travelScheduleStayDays.setText(stayDays);
                                } else {
                                    travelIsStayInfo.setVisibility(View.GONE);
                                    travelScheduleIsStay.setText("否");
                                }
                                travelScheduleTripAllowances.setText(travelTypeName);
                                travelScheduleExpenseDepartment.setText(departmentCostName);
                                travelScheduleDepartureArea.setText(startAddress);
                                travelScheduleDestination.setText(endAddress);

                                travelTabItemTravelCost.setOnClickListener(v -> {
                                    EventBus.getDefault().postSticky(
                                            ChildResult
                                                    .builder()
                                                    .billCode(billCode)
                                                    .data(expenseListBeans)
                                                    .dataName("出差费")
                                                    .build()
                                    );
                                    startActivity(new Intent(mActivity, TabActivity.class));
                                });

                                travelAttachInfo.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false));
                                TravelAdapter travelAdapter = new TravelAdapter(R.layout.fragment_travel_item, fileList);
                                travelAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                                    String fileName = fileList.get(position).getFileName();
                                    String fileUrl = fileList.get(position).getFileUrl();
                                    Intent intent = new Intent(mActivity, OfficeActivity.class);
                                    intent.putExtra("fileName", fileName);
                                    intent.putExtra("fileUrl", fileUrl);
                                    mActivity.startActivity(intent);
                                });
                                travelAttachInfo.setAdapter(travelAdapter);
                                travelAdapter.notifyDataSetChanged();

                                for (TravelOrderInfo.DataBean.WorkPlanListBean data : workPlanListBeans) {
                                    String startDateStr = data.getStartDateStr();
                                    String relatedDepartment = data.getRelatedDepartment();
                                    String relatedPeople = data.getRelatedPeople();
                                    String relatedContent = data.getRelatedContent();
                                    View view = LayoutInflater.from(mActivity).inflate(R.layout.fragment_travel_tab_item, null, false);
                                    LinearLayout tab = view.findViewById(R.id.travel_tab_item);
                                    TextView startDate = view.findViewById(R.id.travel_tab_DatesInclusive);
                                    TextView depart = view.findViewById(R.id.travel_tab_InvolveDepart);
                                    TextView people = view.findViewById(R.id.travel_tab_AssociatedPerson);
                                    TextView content = view.findViewById(R.id.travel_tab_WorkTotal);
                                    startDate.setText(startDateStr);
                                    depart.setText(relatedDepartment);
                                    people.setText(relatedPeople);
                                    content.setText(relatedContent);
                                    travelWorkPlan.addView(tab);
                                }

                                String travelExpenseCost = getDecimal(dataBean.getTravelExpenseCost().doubleValue());
                                String travelExpensePayCost = getDecimal(dataBean.getTravelExpensePayCost().doubleValue());
                                travelTravelSumTravelTotal.setText(travelExpenseCost);
                                travelTravelSumRealTravelTotal.setText(travelExpensePayCost);

                                String budgetInfo = budgetItemObjectBean.getBudgetInfo();
                                String allMoney = getDecimal(budgetItemObjectBean.getAllMoney().doubleValue());
                                String reimbursedMoney = getDecimal(budgetItemObjectBean.getReimbursedMoney().doubleValue());
                                String reimbursingMoney = getDecimal(budgetItemObjectBean.getReimbursingMoney().doubleValue());
                                String remainReimburseMoney = getDecimal(budgetItemObjectBean.getRemainReimburseMoney().doubleValue());
                                String applyedMoney = getDecimal(budgetItemObjectBean.getApplyedMoney().doubleValue());
                                String applyingMoney = getDecimal(budgetItemObjectBean.getApplyingMoney().doubleValue());
                                String remainApplyMoney = getDecimal(budgetItemObjectBean.getRemainApplyMoney().doubleValue());
                                String comInfo = String.format(
                                        forMat,
                                        budgetInfo,
                                        allMoney,
                                        reimbursedMoney,
                                        reimbursingMoney,
                                        remainReimburseMoney,
                                        applyedMoney,
                                        applyingMoney,
                                        remainApplyMoney
                                );
                                travelBudgetInfoTravelCrash.setText(comInfo);

                                for (TravelOrderInfo.DataBean.HistoryListBean bean : historyListBeans) {
                                    String checkType = bean.getCheckType();
                                    if ("A".equals(checkType)) {
                                        View view = LayoutInflater.from(mActivity).inflate(R.layout.fragment_order_process_item, null, false);
                                        LinearLayout linearLayout = view.findViewById(R.id.general_check_Process_Item);
                                        TextView time = view.findViewById(R.id.general_check_Process_Time);
                                        TextView link = view.findViewById(R.id.general_check_Process_Link);
                                        TextView name = view.findViewById(R.id.general_check_Process_Name);
                                        TextView status = view.findViewById(R.id.general_check_Process_Status);
                                        String checkTime = bean.getCheckTimeStr();
                                        String checkAccountUserName = bean.getCheckAccountName();
                                        String processName = bean.getProcessName();
                                        String statusStr = bean.getStatusStr();
                                        time.setText(checkTime);
                                        name.setText(String.format("%s(%s)", checkAccountUserName, processName));
                                        status.setText(statusStr);
                                        if ("待审核".equals(statusStr)) {
                                            time.setTextColor(Color.parseColor("#4a80ef"));
                                            link.setTextColor(Color.parseColor("#4a80ef"));
                                            name.setTextColor(Color.parseColor("#4a80ef"));
                                            status.setTextColor(Color.parseColor("#4a80ef"));
                                        }
                                        travelCheckProcess.addView(linearLayout);
                                    } else if ("C".equals(checkType)) {
                                        View view = LayoutInflater.from(mActivity).inflate(R.layout.fragment_order_process_item, null, false);
                                        LinearLayout linearLayout = view.findViewById(R.id.general_check_Process_Item);
                                        TextView time = view.findViewById(R.id.general_check_Process_Time);
                                        TextView link = view.findViewById(R.id.general_check_Process_Link);
                                        TextView name = view.findViewById(R.id.general_check_Process_Name);
                                        TextView status = view.findViewById(R.id.general_check_Process_Status);
                                        String checkTime = bean.getCheckTimeStr();
                                        String checkAccountUserName = bean.getCheckAccountName();
                                        String processName = bean.getProcessName();
                                        String statusStr = bean.getStatusStr();
                                        time.setText(checkTime);
                                        name.setText(String.format("%s(%s)", checkAccountUserName, processName));
                                        status.setText(statusStr);
                                        if ("待审核".equals(statusStr)) {
                                            time.setTextColor(Color.parseColor("#4a80ef"));
                                            link.setTextColor(Color.parseColor("#4a80ef"));
                                            name.setTextColor(Color.parseColor("#4a80ef"));
                                            status.setTextColor(Color.parseColor("#4a80ef"));
                                        }
                                        travelTravelCheckProcess.addView(linearLayout);
                                    }
                                }
                            } else {
                                ToastUtils.onErrorShowToast("登录态与服务器不一致");
                                initLogoutInfo(mActivity, userName);
                            }
                        } else {
                            ToastUtils.onErrorShowToast("该订单暂无详细信息");
                        }
                    }

                    @Override
                    public void fail(String errorMsg) {
                        ToastUtils.onErrorShowToast(errorMsg);
                    }
                });
    }
}
